package com.parp.visuals;

import java.util.Random;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.media.audiofx.Visualizer;
import android.os.Build;
import android.util.Log;

public class ScopeVisual implements Visual{
	
	private boolean enable = false;

	private final Paint linePaint = new Paint();
	
	private byte[] viz;
	
	private int height;
		
	//Retrieves sound output info for visualisation
	private Visualizer visualizer;
	private boolean vizSupport = (Integer.parseInt(Build.VERSION.SDK) >= 9);
	
	final Random randomGen = new Random(System.currentTimeMillis());
	public ScopeVisual(int height)
	{
		if(vizSupport)
		{
			visualizer = new Visualizer(0);
			visualizer.setEnabled(false);
			visualizer.setCaptureSize(Math.min(Visualizer.getCaptureSizeRange()[1],height));
			viz = new byte[visualizer.getCaptureSize()];
			visualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
	            public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes,
	                    int samplingRate) 
	            {
	            	viz = bytes;
	            }

				@Override
				public void onFftDataCapture(Visualizer visualizer, byte[] fft,
						int samplingRate) {
					// TODO Auto-generated method stub
					
				}
			}, Visualizer.getMaxCaptureRate()/2, true, false);
			visualizer.setEnabled(true);
		}
		this.height = height;
	}
	
	@Override
	public void enable(boolean enable)
	{
		this.enable = enable;
	}
	
	@Override
	public void motionUpdate(int pointerId, float x, float y, long time, int height) {
		//Not needed for this method - updates handled by listener
	}

	@Override
	public void drawVisual(int pointerId, Canvas canvas, float x, float y, long time) {
		int ypoint = 1;
		if(enable && viz != null)
		{
			for(Byte b : viz)
			{
					int p = (b + 128)/2;
					canvas.drawLine(canvas.getWidth()/2 + p, ypoint, canvas.getWidth()/2 - p, ypoint, linePaint);
					//canvas.drawLine(lastByte, i, b, i, linePaint);
					if(b > 10)
					{
					ypoint ++;}
					//Log.i("PARP","loc: " + i + ", value: " + b);
			}
		}
	}
	@Override
	public void up() {
		viz = null;
	}
}
